<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="close">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="role in roleList" :key="role.id" class="el-checkbox" :label="role.id">
        {{ role.name }}
      </el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="assignRole">确定</el-button>
      <el-button size="small" @click="$emit('update:showRoleDialog')">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  name: 'Ar',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 角色列表
      roleList: [],
      // 选中角色的id的数组
      roleIds: [],
      // 添加角色用户的id
      userId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 给员工分配角色
    async assignRole () {
      try {
        await assignRoles({ id: this.userId, roleIds: this.roleIds })
        this.$emit('update:showRoleDialog')

        this.$message.success('用户分配角色成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 查询用户之前分配过的角色
    async getUserRoles (id) {
      const { roleIds } = await getUserDetailById(id)
      // 回显
      this.roleIds = roleIds
      this.userId = id
    },
    async getRoleList () {
      const { rows } = await getRoleList({
        page: 1,
        pagesize: 1000
      })
      // console.log(rows)
      this.roleList = rows
    },
    close () {
      this.$emit('update:showRoleDialog')
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-checkbox {
  margin-bottom: 15px;
}
</style>
